package com.moran.beetlsql.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Description
 * @Author wnf
 * @Date 2025-03-17
 */
@Configuration
public class DataSourceConfig {

    @Primary
    @Bean(name = "mainDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.main")
    public DataSource mainDataSource() {
        return DruidDataSourceBuilder.create().build();
    }


    @Bean(name = "mainJdbcTemplate")
    public JdbcTemplate mainJdbcTemplate(@Qualifier("mainDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    /**
     * 开启事务
     */
    @Bean(name = "transactionManager")
    public DataSourceTransactionManager basicTransactionManager(@Qualifier("mainDataSource") DataSource mainDataSource) {
        DataSourceTransactionManager dsm = new DataSourceTransactionManager();
        dsm.setDataSource(mainDataSource);
        return dsm;
    }


    @Bean(name = "subDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.sub")
    public DataSource subDataSource() {
        return DruidDataSourceBuilder.create().build();
    }


    @Bean(name = "subJdbcTemplate")
    public JdbcTemplate subJdbcTemplate(@Qualifier("subDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean(name = "testDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.test")
    public DataSource testDataSource() {
        return DruidDataSourceBuilder.create().build();
    }


    @Bean(name = "testJdbcTemplate")
    public JdbcTemplate testJdbcTemplate(@Qualifier("testDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}
